/**
 * 接口
 */
var config = require("../config");
var util = require("../util");
var _ljs=require("../mmlog").root("[channel/WeChat-API.js]");

module.exports = {
	/**
	 * 获取用户信息
	 * @param {Object} accessToken 微信令牌
	 * @param {Object} openId 用户OPEN-ID
	 * @param {Object} callback 回掉函数
	 */
	user: function(accessToken, openId, callback) {
		util.get(
			"https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId,
			function(data) {
				_ljs.debug("微信获取用户信息接口:%o", data);
				var _ = {
					name: "",
					image: ""
				}
				if (data.code == 0) {
					_ = {
						name: data.des.nickname,
						image: data.des.headimgurl
					}
				}
				callback(_);
			})
	},
	
	addMenu:function(data,callback){
		var url= "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+config.wechat("at");
		var _data={
			"name":"人工客服",
			"sub_button":[]
		}
		for(var p in data){
			if(data.hasOwnProperty(p)){
				_data.sub_button.push({
					"type":"click",
					"key":"AGENT_EVENT_"+data[p],
					"name":data[p]
				});
			}
		}
		var _r={
			button:[_data]
		}
		console.log(_r);
		util.post(
			url,
			_r,
			function(data) {
				_ljs.debug("回复微信消息结果:\n", data);
				callback && callback(util.result(data.des.errcode));
			}
		)
	},

	reply: function(openId, param, callback) {
		var _data = {
			touser: openId,
			msgtype: param.type
		}
		if(param.type=="text"){
			_data.text={
				content: param.content
			}
		}else if(param.type=="image"){
			_data.image={
				media_id:param.content
			}
		}
		
		_ljs.debug("回复微信消息:\n", _data);
		util.post(
			"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + config.wechat("at"),
			_data,
			function(data) {
				data.code = data.des.errcode;
				_ljs.debug("回复微信消息结果:\n", data);
				callback && callback(data);
			}
		)
	}
}